<template>
  <div>
    <!-- 温馨提示 -->
    <div style="background-color: #fffbe6; padding: 10px; border: 1px solid #ffe58f; margin-bottom: 16px;">
      <span style="color: #d48806;">温馨提示：1. 查看优惠券领取记录  2. 未使用的优惠券可以作废 !</span>
    </div>

    <!-- 筛选区域 -->
    <a-row class="seach-row">
      <a-col :xs="24" :sm="12" :md="8" :lg="6" :xl="5">
        <a-form-item label="用户信息" style="display: flex;align-items: center">
          <a-input v-model="search.username" placeholder="请输入用户编号/昵称" style="width: 100%"/>
        </a-form-item>
      </a-col>
      <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="5">
        <a-form-item label="优惠券名称" style="display: flex;align-items: center">
          <a-input v-model="search.couponName" placeholder="请输入优惠券名称" style="width: 100%"/>
        </a-form-item>
      </a-col>
      <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="5">
        <a-form-item label="领取方式" style="display: flex;align-items: center">
          <a-select v-model="search.channel" placeholder="请选择" style="width: 100%;min-width: 200px">
            <a-select-option value="all">全部</a-select-option>
            <a-select-option value="good">用户领取</a-select-option>
            <a-select-option value="bad">系统发放</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
        <a-form-item label="发放人" style="display: flex;align-items: center">
          <a-select v-model="search.sender" placeholder="请选择" style="width: 100%;min-width: 200px">
            <a-select-option value="all">全部</a-select-option>
            <a-select-option value="good">全场通用</a-select-option>
            <a-select-option value="bad">指定商品可用</a-select-option>
            <a-select-option value="other">指定分类可用</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>

      <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
        <a-form-item label="领取时间" style="display: flex;align-items: center">
          <a-range-picker v-model="search.receiveTime"/>
        </a-form-item>
      </a-col>

      <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8">
        <a-button type="primary" @click="handleSearch" class="search-btn">查询</a-button>
        <a-button @click="handleReset" class="reset-btn" style="margin-left: 30px">重置</a-button>
      </a-col>
    </a-row>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 状态栏 -->
      <a-tabs>
        <a-tab-pane key="all" :tab="`全部（${allCount} ）`"></a-tab-pane>
        <a-tab-pane key="notused" :tab="`未使用（${notusedCount}）`"></a-tab-pane>
        <a-tab-pane key="pending" :tab="`已使用（${pendingCount}）`"></a-tab-pane>
        <a-tab-pane key="replied" :tab="`已过期（${repliedCount}）`"></a-tab-pane>
        <a-tab-pane key="end" :tab="`已作废（${endCount}）`"></a-tab-pane>
      </a-tabs>

      <!-- 表格区域 -->
      <a-table :data-source="filteredData" :columns="columns" rowKey="id">
        <template v-slot:action>
          <a-button type="link">查看订单</a-button>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      defaultActive: 'all',
      selectedRows: [],  // 用于存储选中的行的 key
      search: {
        username: '',
        couponName: '',
        channel: 'all',
        sender: 'all',
        receiveTime: [],
      },
      allCount: 0,
      notusedCount: 0,
      pendingCount: 0,
      repliedCount: 0,
      endCount: 0,
      dataSource: [
        // {
        //   id: '2',
        //   username: '张三',
        //   couponName: '优惠券2',
        //   channel: '系统发放',
        //   useTime: '2023-06-02',
        //   invalidTime: '2023-06-11',
        //   status: '已使用',
        //   createTime: '2023-06-06',
        // },
        // {
        //   id: '3',
        //   username: '李四',
        //   couponName: '优惠券3',
        //   channel: '用户领取',
        //   useTime: '2023-06-03',
        //   invalidTime: '2023-06-12',
        //   status: '已作废',
        //   createTime: '2023-06-07',
        // },
      ],
      filteredData: [],
      columns: [
        {
          title: '用户信息',
          dataIndex: 'userName',
        },
        {
          title: '优惠券名称',
          dataIndex: 'couponName',
        },
        {
          title: '领取方式',
          dataIndex: 'channel',
        },
        {
          title: '领取时间',
          dataIndex: 'createTime',
        },
        {
          title: '过期时间',
          dataIndex: 'invalidTime',
        },
        {
          title: '使用状态',
          dataIndex: 'status',
        },
        {
          title: '操作',
          scopedSlots: {customRender: 'action'},
        },
      ],
    };
  },
  methods: {
    async fetchcoupon() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/coupon/infoAllCoupongetAll`, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          const orderData = response.data.data.reverse();
          for (let i = 0; i < orderData.length; i++) {
            orderData[i].Time = orderData[i].getTimeStart + "——" + orderData[i].getTimeEnd;
          }
          this.dataSource = orderData;
          this.filteredData = [...this.dataSource];
          console.log(this.dataSource)
          this.updateCounts();
        } else {
          console.error('获取订单信息失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    filterData() {
      const fetch = this.dataSource.filter(item => {
        return (
            (this.search.username ? item.username.includes(this.search.username) : true) &&
            (this.search.couponName ? item.couponName.includes(this.search.couponName) : true) &&
            (this.search.channel !== 'all' ? item.channel === this.search.channel : true) &&
            (this.search.sender !== 'all' ? item.sender === this.search.sender : true) &&
            (this.search.receiveTime.length === 0 || (item.time >= this.search.receiveTime[0] && item.time <= this.search.receiveTime[1]))
        );
      });
      this.filteredData = fetch; // 更新filteredData
    },

    // 更新统计信息
    updateCounts() {
      this.allCount = this.filteredData.length;
      this.notusedCount = this.filteredData.filter(item => item.status === 'UNUSED').length;
      this.pendingCount = this.filteredData.filter(item => item.status === 'USED').length;
      this.repliedCount = this.filteredData.filter(item => item.status === '已过期').length;
      this.endCount = this.filteredData.filter(item => item.status === '已作废').length;
    },

    // Tab栏切换时触发的函数
    handleChange(key) {
      this.defaultActive = key;
      this.filterDataSource(); // 切换Tab时调用过滤方法
    },

    filterDataSource() {
      let filtered = [...this.dataSource]; // 克隆原始数据

      // 根据当前Tab过滤数据
      switch (this.defaultActive) {
        case 'all':
          break;
        case 'notused':
          filtered = filtered.filter(item => item.status === 'UNUSED');
          break;
        case 'pending':
          filtered = filtered.filter(item => item.status === 'USED');
          break;
        case 'replied':
          filtered = filtered.filter(item => item.status === '已结束');
          break;
        default:
          break;
      }
      // 更新过滤后的数据
      this.filteredData = filtered;

      // 更新数据统计
      // this.updateCounts();
    },

    // 搜索功能
    handleSearch() {
      this.filterData();
      this.updateCounts();
    },

    // 重置筛选条件
    handleReset() {
      this.search = {
        username: '',
        couponName: '',
        channel: 'all',
        sender: 'all',
        receiveTime: [],
      };
      this.filteredData = [...this.dataSource];
      this.updateCounts();
    },

  },
  mounted() {
    this.fetchcoupon()
    this.updateCounts();
  },
};
</script>

<style scoped>

</style>
